package com.zsr.web.controller.message;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zsr.common.config.DingTaikConfig;
import com.zsr.common.utils.ding.DingCallbackCrypto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 钉钉消息订阅
 */
@Slf4j
@EnableAsync
@RestController
@RequestMapping("/ding/talk")
public class DingdingMessageController {


    @Autowired
    private DingTaikConfig dingTaikConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 事件回调，钉钉入职事件
     */
    @PostMapping("/dingMsg")
    public Map<String, String> dMessage(@RequestParam(value = "msg_signature", required = false) String msg_signature,
                                        @RequestParam(value = "timestamp", required = false) String timeStamp,
                                        @RequestParam(value = "nonce", required = false) String nonce,
                                        @RequestBody(required = false) JSONObject json) {
        try {
            log.info("dMessage~msg_signature=={}，timeStamp=={}，nonce=={}，json=={}", msg_signature, timeStamp, nonce, json.toString());
            // 1. 从http请求中获取加解密参数
            // 2. 使用加解密类型
            // Constant.OWNER_KEY 说明：
            // 1、开发者后台配置的订阅事件为应用级事件推送，此时OWNER_KEY为应用的APP_KEY。
            // 2、调用订阅事件接口订阅的事件为企业级事件推送，
            //      此时OWNER_KEY为：企业的appkey（企业内部应用）或SUITE_KEY（三方应用）
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(dingTaikConfig.getToken(), dingTaikConfig.getEncodingAesKey(), dingTaikConfig.getAppKey());
            String encryptMsg = json.getString("encrypt");
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);
            // 3. 反序列化回调事件json数据
            JSONObject eventJson = JSON.parseObject(decryptMsg);
            log.info("dMessage~eventJson=={}", eventJson);
            String eventType = eventJson.getString("EventType");
            Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
            if ("1".equals(redisTemplate.opsForValue().get("DDMSG:" + eventJson.getString("eventId")))) {
                return successMap;
            }
            redisTemplate.opsForValue().set("DDMSG:" + eventJson.getString("eventId"), "1", 1, TimeUnit.DAYS);
            // 4. 根据EventType分类处理
            if ("check_url".equals(eventType)) {
                // 测试回调url的正确性
                log.info("测试回调url的正确性");
                return successMap;
            }
        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
        }
        return null;
    }



}
